<template>
  <div class="customer-management-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/dealer' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>客户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="main-card">
      <div class="card-header">
        <h3>客户列表</h3>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddCustomer">新增客户</el-button>
      </div>

      <!-- 搜索区域 -->
<!--      <div class="search-area">-->
<!--        <el-form :inline="true" :model="searchForm" class="search-form">-->
<!--          <el-form-item label="客户名称">-->
<!--            <el-input v-model="searchForm.name" placeholder="请输入客户名称" clearable></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="联系电话">-->
<!--            <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="客户分类">-->
<!--            <el-select v-model="searchForm.category" placeholder="请选择" clearable>-->
<!--              <el-option label="批发商" value="wholesale"></el-option>-->
<!--              <el-option label="零售商" value="retail"></el-option>-->
<!--              <el-option label="个人" value="individual"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item>-->
<!--            <el-button type="primary" icon="el-icon-search" @click="searchCustomers">搜索</el-button>-->
<!--            <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>-->
<!--          </el-form-item>-->
<!--        </el-form>-->
<!--      </div>-->

      <!-- 客户列表 -->
      <el-table
        :data="customerList"
        border
        style="width: 100%"
        v-loading="loading">
        <el-table-column prop="name" label="客户名称" width="150"></el-table-column>
        <el-table-column prop="contact" label="联系人" width="100"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="category" label="客户分类" width="100">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">{{ getCategoryLabel(scope.row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column label="订单数" width="80" align="center">
          <template #default="scope">
            <el-button type="text" @click="viewOrders(scope.row)">{{ scope.row.orderCount }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="lastOrderDate" label="最近订单" width="100"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleViewCustomer(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleEditCustomer(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="createOrder(scope.row)">下单</el-button>
            <el-button type="text" size="small" style="color: #F56C6C" @click="handleDeleteCustomer(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑客户对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="customerForm" :rules="customerRules" ref="customerFormRef" label-width="80px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="customerForm.name" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="customerForm.contact" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="customerForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="客户分类" prop="category">
          <el-select v-model="customerForm.category" placeholder="请选择" style="width: 100%">
            <el-option label="批发商" value="wholesale"></el-option>
            <el-option label="零售商" value="retail"></el-option>
            <el-option label="个人" value="individual"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="customerForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="customerForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCustomerForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 客户详情对话框 -->
    <el-dialog title="客户详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户名称">{{ currentCustomer.name }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ currentCustomer.contact }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentCustomer.phone }}</el-descriptions-item>
        <el-descriptions-item label="客户分类">{{ getCategoryLabel(currentCustomer.category) }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ currentCustomer.address }}</el-descriptions-item>
        <el-descriptions-item label="订单数量">{{ currentCustomer.orderCount }}</el-descriptions-item>
        <el-descriptions-item label="最近订单">{{ currentCustomer.lastOrderDate }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentCustomer.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <div class="detail-title">最近订单</div>
      <el-table :data="currentCustomerOrders" style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="120"></el-table-column>
        <el-table-column prop="date" label="订单日期" width="100"></el-table-column>
        <el-table-column prop="product" label="产品名称"></el-table-column>
        <el-table-column prop="amount" label="金额" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { customerAPI, orderAPI } from '@/api/api'

export default {
  name: 'CustomerManagementPageView',
  data() {
    return {
      loading: false,
      searchForm: {
        name: '',
        phone: '',
        category: ''
      },
      customerList: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增客户',
      customerForm: {
        id: null,
        name: '',
        contact: '',
        phone: '',
        category: '',
        address: '',
        remark: ''
      },
      customerRules: {
        name: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择客户分类', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ]
      },
      detailDialogVisible: false,
      currentCustomer: {},
      currentCustomerOrders: []
    }
  },
  created() {
    this.fetchCustomers()
  },
  methods: {
    // 获取客户列表
    fetchCustomers() {
      this.loading = true
      const params = {
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        name: this.searchForm.name || undefined,
        phone: this.searchForm.phone || undefined,
        category: this.searchForm.category || undefined
      }
      
      customerAPI.getCustomers(params)
        .then(response => {
          if (response.code === 200) {
            this.customerList = response.data.list || []
            this.pagination.total = response.data.total || 0
          } else {
            this.$message.error(response.message || '获取客户列表失败')
          }
        })
        .catch(error => {
          console.error('Fetch customers error:', error)
          this.$message.error('获取客户列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    searchCustomers() {
      this.pagination.currentPage = 1
      this.fetchCustomers()
    },
    
    resetSearch() {
      this.searchForm = {
        name: '',
        phone: '',
        category: ''
      }
      this.searchCustomers()
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchCustomers()
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchCustomers()
    },
    
    // 查看客户详情
    viewCustomerDetail(row) {
      this.loading = true
      customerAPI.getCustomerById(row.id)
        .then(response => {
          if (response.code === 200) {
            this.currentCustomer = response.data
            // 获取客户订单
            this.fetchCustomerOrders(row.id)
            this.detailDialogVisible = true
          } else {
            this.$message.error(response.message || '获取客户详情失败')
          }
        })
        .catch(error => {
          console.error('View customer error:', error)
          this.$message.error('获取客户详情失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 获取客户订单
    fetchCustomerOrders(customerId) {
      orderAPI.getOrders({ customerId })
        .then(response => {
          if (response.code === 200) {
            this.currentCustomerOrders = response.data.list || []
          } else {
            this.currentCustomerOrders = []
          }
        })
        .catch(error => {
          console.error('Fetch customer orders error:', error)
          this.currentCustomerOrders = []
        })
    },
    getCategoryType(category) {
      const typeMap = {
        'wholesale': 'primary',
        'retail': 'success',
        'individual': 'info'
      }
      return typeMap[category] || ''
    },
    getCategoryLabel(category) {
      const labelMap = {
        'wholesale': '批发商',
        'retail': '零售商',
        'individual': '个人'
      }
      return labelMap[category] || category
    },
    getStatusType(status) {
      const typeMap = {
        '待发货': 'warning',
        '已发货': 'primary',
        '运输中': 'info',
        '已完成': 'success'
      }
      return typeMap[status] || ''
    },
    handleAddCustomer() {
      this.dialogTitle = '新增客户'
      this.customerForm = {
        id: null,
        name: '',
        contact: '',
        phone: '',
        category: '',
        address: '',
        remark: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.customerFormRef && this.$refs.customerFormRef.clearValidate()
      })
    },
    handleEditCustomer(row) {
      this.dialogTitle = '编辑客户'
      this.customerForm = { ...row }
      this.dialogVisible = true
    },
    handleViewCustomer(row) {
      this.viewCustomerDetail(row)
    },
    handleDeleteCustomer(row) {
      this.$confirm('确认删除该客户吗？此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中，这里应该调用API删除客户
        const index = this.customerList.findIndex(item => item.id === row.id)
        if (index !== -1) {
          this.customerList.splice(index, 1)
          this.pagination.total--
        }
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    submitCustomerForm() {
      this.$refs.customerFormRef.validate(valid => {
        if (!valid) return

        // 实际项目中，这里应该调用API提交表单
        if (this.customerForm.id) {
          // 更新客户
          const index = this.customerList.findIndex(item => item.id === this.customerForm.id)
          if (index !== -1) {
            this.customerList[index] = { ...this.customerList[index], ...this.customerForm }
          }
          this.$message.success('更新成功')
        } else {
          // 新增客户
          const newCustomer = {
            ...this.customerForm,
            id: Math.floor(Math.random() * 1000) + 10,
            orderCount: 0,
            lastOrderDate: '-'
          }
          this.customerList.unshift(newCustomer)
          this.pagination.total++
          this.$message.success('添加成功')
        }

        this.dialogVisible = false
      })
    },
    viewOrders(row) {
      this.$router.push({
        path: '/dealer/order-management',
        query: { customerId: row.id }
      })
    },
    createOrder(row) {
      this.$router.push({
        path: '/dealer/order-management/create',
        query: { customerId: row.id }
      })
    }
  }
}
</script>

<style scoped>
.customer-management-container {
  padding: 20px;
}

.el-breadcrumb {
  margin-bottom: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.search-area {
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px 0;
  padding-left: 8px;
  border-left: 3px solid #409EFF;
}
</style>
